#!/usr/bin/env python
# coding=utf-8
from tracker.types import track_item

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

__author__ = 'vavava'

from vavava.db_connector import DBConnector
from threading import Lock





class Tracking(object):
    def __init__(self,db_name="wr_trace",dbObj=None,host="localhost",
                 port=3306,user="root",passwd="root",db="wr_trace"):
        if dbObj:
            self.conn=dbObj
        else:
            self.conn=DBConnector(host,port,user,passwd,db)
        self.cursor=self.conn.get_cursor()
        self.db_name=db_name
        self.mutex = Lock()

    def __del__(self):
        self.cursor.close()
        self.conn.conn.close()

    def insert(self,data=TrackItem.TrackItem()):
        """ update row to db
             查询和写入时没做回滚处理
        """
        self.mutex.acquire()  # ??? 没有处理异常
        try:
            TrackTime=self.date2str(data.TrackTime)
            Created=self.date2str(data.Created)
            Modified=self.date2str(data.Modified)
            sql_str=r"insert into %s.Tracking(Name,TrackTime,Description,Location,Created,Modified) "\
                    r"select '%s','%s','%s','%s','%s','%s' from dual where not exists "\
                    r"(select 1 from %s.Tracking where Name='%s' and TrackTime='%s' and Description='%s' and Location='%s')"\
                    %(self.db_name,data.Name,TrackTime,data.Description,data.Location,Created,Modified,
                      self.db_name,data.Name,TrackTime,data.Description,data.Location )
            self.cursor.execute(sql_str)
            self.conn.conn.commit()
        except:
            self.mutex.release()
            return None
        return True

    def date2str(self,time_s):
        from time import strftime
        if time_s is None:
            return "0000-00-00 00:00"
        try:
            return strftime("%Y-%m-%d %H:%M:%S",time_s)
        except Exception as e:
            return "0000-00-00 00:00"

    def getTopN(self,n=1,conditions={}):
        """ get latest rows """
        self.mutex.acquire()
        sql_str=r"select * from %s.Tracking where"%self.db_name
        for condition in conditions:
            sql_str+=r"%=%"%(condition,conditions.get(condition))
        else:
            sql_str=r"select * from %s.Tracking "%self.db_name
        self.cursor.execute(sql_str)
        result=self.cursor.fetchmany(n)
        re_list=[]
        for each in result:
            re_list.append(track_item.TrackItem(each[0],each[1],each[2],each[3],each[4], each[5],each[6], each[7]))
        self.mutex.release()
        return re_list



def test():
    import time
    row= track_item.TrackItem(
        Name        = "UCL0003192",
        TrackTime   = time.strptime("14/09/12 17:03", "%d/%m/%y %H:%M") ,
        Description = "Description ",
        Location    = "Location    ",
        Created     = time.strptime("14/09/12 17:03", "%d/%m/%y %H:%M") ,
        Modified    = time.strptime("14/09/12 17:03", "%d/%m/%y %H:%M") ,
    )
    trace=Tracking(passwd='root')

    if True:
        result=trace.getTopN(3)
        for each in result:
            print(each.ID)
    else:
        for pos in range(0,9):
            trace.insert(row)


if __name__ == '__main__':
    test()



